import React, { Component } from 'react';
import './toast.scss';
import Animated from 'animated/lib/targets/react-dom';

/*
  使用方式:
  引入Toast，render 组件 <Toast ref="toast"></Toast>
  在需要使用的地方 this.refs.toast.showToast(text, duration = 3)
*/

class Toast extends Component {
  constructor (...args) {
    super(...args);
    this.state = {
      anim: new Animated.Value(0),
      show: false,
      text: ''
    }
  }
  showToast (text, duration = 3) {
    this.setState({
      show: true,
      text
    });
    Animated.timing(this.state.anim, {
      toValue: 1,
      duration: 300
    }).start();

    let timer = setTimeout(() => {
      this.setState({
        show: false,
        text: ''
      });
      clearTimeout(timer);
    }, duration * 1000);
  }
  render () {
    return (
      <div>
        {
          this.state.show ? (
            <Animated.div
              className="toast"
              style={{opacity: this.state.anim}}
            >
              {this.state.text}
            </Animated.div>
          ) : ''
        }
      </div>
    );
  }
}

export default Toast;
